//
//  AddressView.m
//  AddressTest
//
//  Created by weizhongming on 2017/2/15.
//  Copyright © 2017年 航磊_. All rights reserved.
//

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define IPHONE6_SIZE SCREEN_WIDTH/375
#define RGB(r, g, b)  [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

#import "AddressView.h"
#import "MJExtension.h"
#import "AppUtils.h"
#import <Masonry.h>
#import "BankAddressModelPack.h"
@implementation AddressView


- (instancetype)initWithFrame:(CGRect)frame WithTitle:(NSString *)title{

    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5f];
        
        UIView *tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -400 *IPHONE6_SIZE)];
        tapView.userInteractionEnabled = YES;
        [self addSubview:tapView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
        [tapView addGestureRecognizer:tap];
        
//      获取数据源
        NSArray *arr = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];
        NSArray *myArray = [CityVO mj_objectArrayWithKeyValuesArray:arr];
        
        /*
        NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/xljy/getcityjson"];
        [[ETONEHttpClient sharedInstance] doHTTPSPOSTNOTips:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
            
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
            
            BankAddressResponse *bankresponse = [BankAddressResponse mj_objectWithKeyValues:responseObject];
            
            NSLog(@"%@",bankresponse.response);
            NSMutableArray *testArrar = [NSMutableArray array];
            for (BankAddressResponseData *data in bankresponse.response) {
                NSLog(@"%@",data.pro);
                CityVO *cityVO = [[CityVO alloc] init];
                cityVO.state = data.pro;
                for (BankAddressResponseRecord *record in data.children) {
                    CitiesVO *citiesVo = [[CitiesVO alloc] init];
                    citiesVo.city = record.city;
                    NSLog(@"%@",record.city);
                }
                [testArrar addObject:cityVO];
            }
            NSLog(@"%@",testArrar);
            
        } FailedHandler:^(NSError *error) {
            
        }];
         
         */
        //处理后端返回的数据  按首字母排序
        NSMutableDictionary *addressBookDict = [NSMutableDictionary dictionary];
        for (CityVO *cityVO in myArray) {
            NSString *firstLetterString = [AddressView getFirstLetterFromString:cityVO.state];
            if (addressBookDict[firstLetterString]) {
                [addressBookDict[firstLetterString] addObject:cityVO];
            }else
            {
                //创建新发可变数组存储该首字母对应的联系人模型
                NSMutableArray *arrGroupNames = [NSMutableArray arrayWithObject:cityVO];
                //将首字母-姓名数组作为key-value加入到字典中
                [addressBookDict setObject:arrGroupNames forKey:firstLetterString];
            }
        }
        NSArray *nameKeys = [[addressBookDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
        
        NSMutableArray *array2 = [NSMutableArray array];
        for (NSString *str in nameKeys) {
            [array2 addObject:addressBookDict[str]];
        }
        
        self.datasArr = [array2 copy];
        
        
        self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 400 *IPHONE6_SIZE)];
        self.myView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.myView];
        
        [self addTitleView];
    }
    return self;
}



#pragma mark - 获取联系人姓名首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)getFirstLetterFromString:(NSString *)aString
{
    /**
     * **************************************** START ***************************************
     * 之前PPGetAddressBook对联系人排序时在中文转拼音这一部分非常耗时
     * 参考博主-庞海礁先生的一文:iOS开发中如何更快的实现汉字转拼音 http://www.olinone.com/?p=131
     * 使PPGetAddressBook对联系人排序的性能提升 3~6倍, 非常感谢!
     */
    NSMutableString *mutableString = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
    NSString *pinyinString = [mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    /**
     *  *************************************** END ******************************************
     */
    
    // 将拼音首字母装换成大写
    NSString *strPinYin = [[self polyphoneStringHandle:aString pinyinString:pinyinString] uppercaseString];
    // 截取大写首字母
    NSString *firstString = [strPinYin substringToIndex:1];
    // 判断姓名首位是否为大写字母
    NSString * regexA = @"^[A-Z]$";
    NSPredicate *predA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexA];
    // 获取并返回首字母
    return [predA evaluateWithObject:firstString] ? firstString : @"#";
    
}

/**
 多音字处理
 */
+ (NSString *)polyphoneStringHandle:(NSString *)aString pinyinString:(NSString *)pinyinString
{
    if ([aString hasPrefix:@"长"]) { return @"chang";}
    if ([aString hasPrefix:@"沈"]) { return @"shen"; }
    if ([aString hasPrefix:@"厦"]) { return @"xia";  }
    if ([aString hasPrefix:@"地"]) { return @"di";   }
    if ([aString hasPrefix:@"重"]) { return @"chong";}
    return pinyinString;
}

- (void)addTitleView{
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15 - 16, 14, 16, 16)];
    [button setImage:[UIImage imageNamed:@"icon_off"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(tapClick) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:button];
    
    self.selectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, 75, 20)];
    self.selectLabel.textColor = RGB(51, 51, 51);
    self.selectLabel.text = @"请选择";
    self.selectLabel.font = [UIFont systemFontOfSize:15.f];
    self.selectLabel.textAlignment = NSTextAlignmentCenter;
    self.selectLabel.userInteractionEnabled = YES;
    [self.myView addSubview:self.selectLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectLabelTapClick)];
    [self.selectLabel addGestureRecognizer:tap];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.selectLabel.frame) + 12, SCREEN_WIDTH, 1)];
    lineView.backgroundColor = RGB(229, 229, 229);
    [self.myView addSubview:lineView];
    
    self.redLineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.selectLabel.frame) +15, CGRectGetMaxY(self.selectLabel.frame) + 11, 45, 2)];
    self.redLineView.layer.cornerRadius = 1;
    self.redLineView.backgroundColor = RGB(91, 113, 255);
    [self.myView addSubview:self.redLineView];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.redLineView.frame), SCREEN_WIDTH, self.myView.frame.size.height - CGRectGetMaxY(self.redLineView.frame))];
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, self.scrollView.frame.size.height);
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    [self.myView addSubview:self.scrollView];
    
    self.tableView1 = [[AddressTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.scrollView.frame.size.height) withParmas:self.datasArr];
   
    __weak __typeof(self)weakSelf = self;


    self.tableView1.block = ^(NSIndexPath *indexPath){
        
        //显示"请选择"
        weakSelf.selectLabel.hidden = NO;
        
    
        [weakSelf.cityLabel removeFromSuperview];
        weakSelf.cityLabel = nil;
        
        weakSelf.oneCityVo = weakSelf.datasArr[indexPath.section][indexPath.row];
        weakSelf.stateLabel.frame = CGRectMake(10, 12, 30 + [AppUtils widthOfString:weakSelf.oneCityVo.state font:14 height:30 *IPHONE6_SIZE], 20);
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            weakSelf.selectLabel.frame = CGRectMake(CGRectGetMaxX(weakSelf.stateLabel.frame), 12, 75, 20);
            weakSelf.redLineView.frame = CGRectMake(CGRectGetMinX(weakSelf.selectLabel.frame) +15, 42, 45, 2);
        } completion:^(BOOL finished) {
            
            weakSelf.stateLabel.text = weakSelf.oneCityVo.state;
        }];
        
        weakSelf.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH *2, weakSelf.scrollView.frame.size.height);
       
        [weakSelf.tableView2 removeFromSuperview];
        weakSelf.tableView2 = nil;
        
        [weakSelf.tableView3 removeFromSuperview];
        weakSelf.tableView3 = nil;
        
        
        
        
        
        
        //处理后端返回的数据  按首字母排序
        NSMutableDictionary *addressBookDict = [NSMutableDictionary dictionary];
        for (CitiesVO *cityVO in weakSelf.oneCityVo.cities) {
            NSString *firstLetterString = [AddressView getFirstLetterFromString:cityVO.city];
            if (addressBookDict[firstLetterString]) {
                [addressBookDict[firstLetterString] addObject:cityVO];
            }else
            {
                //创建新发可变数组存储该首字母对应的联系人模型
                NSMutableArray *arrGroupNames = [NSMutableArray arrayWithObject:cityVO];
                //将首字母-姓名数组作为key-value加入到字典中
                [addressBookDict setObject:arrGroupNames forKey:firstLetterString];
            }
        }
        NSArray *nameKeys = [[addressBookDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
        
        NSMutableArray *array2 = [NSMutableArray array];
        for (NSString *str in nameKeys) {
            [array2 addObject:addressBookDict[str]];
        }
        
        
//        weakSelf.datasArr1 = weakSelf.oneCityVo.cities;
        weakSelf.datasArr1 = [array2 copy];
        
        
        
        weakSelf.tableView2.hidden = NO;
        
        [weakSelf.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
    };
    [self.scrollView addSubview:self.tableView1];
}

#pragma mark -- UIScrollView Delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    NSLog(@"%f",scrollView.contentOffset.x /SCREEN_WIDTH);
    
    if (scrollView.contentOffset.x /SCREEN_WIDTH == 0) {
        
        [UIView animateWithDuration:0.5f animations:^{
        
            self.redLineView.frame = CGRectMake(22, 42, [AppUtils widthOfString:self.stateLabel.text font:15 height:30 *IPHONE6_SIZE], 2);

        }];
        
    }else if (scrollView.contentOffset.x /SCREEN_WIDTH ==1){
    
        if (_cityLabel) {
            
            
            [UIView animateWithDuration:0.5f animations:^{
                
                self.redLineView.frame = CGRectMake(CGRectGetMaxX(self.stateLabel.frame) +15, 42, [AppUtils widthOfString:self.cityLabel.text font:15 height:30 *IPHONE6_SIZE], 2);
            }];
        }else{
            
            
            [UIView animateWithDuration:0.5f animations:^{
                
                self.redLineView.frame = CGRectMake(CGRectGetMaxX(self.stateLabel.frame) +15, 42, 45, 2);
            }];
        }
    }else{
    
        [UIView animateWithDuration:0.5f animations:^{

            self.redLineView.frame = CGRectMake(CGRectGetMinX(self.selectLabel.frame) +15, 42, 45, 2);
        }];
    }
}

- (UILabel *)stateLabel{

    if (!_stateLabel) {
        
        _stateLabel = [[UILabel alloc] init];
        _stateLabel.font = [UIFont systemFontOfSize:15.f];
        _stateLabel.textAlignment = NSTextAlignmentCenter;
        _stateLabel.userInteractionEnabled = YES;
        [self.myView addSubview:_stateLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelTapClick)];
        [_stateLabel addGestureRecognizer:tap];
    }
    return _stateLabel;
}

- (void)stateLabelTapClick{

    [UIView animateWithDuration:0.5f animations:^{
        
        self.redLineView.frame = CGRectMake(15, 42, [AppUtils widthOfString:self.stateLabel.text font:15 height:30 *IPHONE6_SIZE], 2);
        
    }];
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (UILabel *)cityLabel{

    if (!_cityLabel) {
        
        _cityLabel = [[UILabel alloc] init];
        _cityLabel.font = [UIFont systemFontOfSize:15.f];
        _cityLabel.textAlignment = NSTextAlignmentCenter;
        _cityLabel.userInteractionEnabled = YES;
        [self.myView addSubview:_cityLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cityLabelTapClick)];
        [_cityLabel addGestureRecognizer:tap];
    }
    return _cityLabel;
}

- (void)cityLabelTapClick{

    [UIView animateWithDuration:0.5f animations:^{
        
        self.redLineView.frame = CGRectMake(CGRectGetMaxX(self.stateLabel.frame) +15, 42, [AppUtils widthOfString:self.cityLabel.text font:15 height:30 *IPHONE6_SIZE], 2);
    }];
    [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
}

- (void)selectLabelTapClick{

    
    [UIView animateWithDuration:0.5f animations:^{
        
        self.redLineView.frame = CGRectMake(CGRectGetMinX(self.selectLabel.frame) +15, 42, 45, 2);
    }];

    if (_cityLabel) {
        
        
        [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH *2, 0) animated:YES];
    }else if (_stateLabel){
    
        
        [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
    }
}

- (AddressTableView *)tableView2{

    if (!_tableView2) {
        
        __weak __typeof(self)weakSelf = self;

        _tableView2 = [[AddressTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, self.scrollView.frame.size.height) withParmas:self.datasArr1];
        _tableView2.block = ^(NSIndexPath *indexPath){
        
            weakSelf.twoCitiesVO = weakSelf.datasArr1[indexPath.section][indexPath.row];

            weakSelf.cityLabel.frame = CGRectMake(CGRectGetMaxX(weakSelf.stateLabel.frame), 12, 30 + [AppUtils widthOfString:weakSelf.twoCitiesVO.city font:15 height:30 *IPHONE6_SIZE], 20);
            
            
            weakSelf.redLineView.frame = CGRectMake(CGRectGetMaxX(weakSelf.stateLabel.frame) +15, 42, [AppUtils widthOfString:weakSelf.twoCitiesVO.city font:15 height:30 *IPHONE6_SIZE], 2);
            
            
            
            //隐藏"请选择"
            weakSelf.selectLabel.hidden = YES;
            
            weakSelf.cityLabel.text = weakSelf.twoCitiesVO.city;

            [UIView animateWithDuration:0.5 animations:^{
                
                
            } completion:^(BOOL finished) {
                
                //退出弹窗
                [weakSelf tapClick];
                
                weakSelf.block([NSString stringWithFormat:@"%@ %@ %@",weakSelf.oneCityVo.state,weakSelf.twoCitiesVO.city,@""]);
                
            }];
            
            weakSelf.datasArr2 = weakSelf.twoCitiesVO.areas;
            
            [weakSelf.tableView3 removeFromSuperview];
            weakSelf.tableView3 = nil;

            weakSelf.tableView3.hidden = NO;

        };
        [self.scrollView addSubview:_tableView2];
    }
    
    return _tableView2;
}

- (AddressTableView *)tableView3{

    if (!_tableView3) {
        
        __weak __typeof(self)weakSelf = self;

        _tableView3 = [[AddressTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH *2, 0, SCREEN_WIDTH, weakSelf.scrollView.frame.size.height) withParmas:self.datasArr2];
        _tableView3.block = ^(NSIndexPath *indexPath){
            
//            [weakSelf tapClick];
//            weakSelf.block([NSString stringWithFormat:@"%@ %@ %@",weakSelf.oneCityVo.state,weakSelf.twoCitiesVO.city,weakSelf.datasArr2[row]]);
        };
        [self.scrollView addSubview:_tableView3];
    }
    
    return _tableView3;
}

#pragma mark -- 点击空白处触发
- (void)tapClick{

    [UIView animateWithDuration:0.5f animations:^{
        
        self.myView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 400 *IPHONE6_SIZE);
    } completion:^(BOOL finished) {
        
        self.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_WIDTH);
//        [self removeFromSuperview];

    }];
}

#pragma mark -- 弹出选择地址view
- (void)showView:(UIView *)supView{

    self.fatherView = supView;
    
    [UIView animateWithDuration:0.5f animations:^{
        
        self.myView.frame = CGRectMake(0, SCREEN_HEIGHT -400 *IPHONE6_SIZE, SCREEN_WIDTH, 400 *IPHONE6_SIZE);
//        [supView.layer setTransform:[self firstTransform]];
        
    } completion:^(BOOL finished) {
        
//        [UIView animateWithDuration:0.5 animations:^{
//            supView.transform = CGAffineTransformMakeScale(0.9, 0.9);
//        }];
    }];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}

// 后靠效果
- (CATransform3D)firstTransform{
    
    CATransform3D t1 = CATransform3DIdentity;
    t1.m34 = 1.0/-900;
    //带点缩小的效果
    t1 = CATransform3DScale(t1, 0.95, 0.95, 1);
    //绕x轴旋转
    t1 = CATransform3DRotate(t1, 15.0 * M_PI/180.0, 1, 0, 0);
    return t1;
}

@end
